import os
import subprocess
import time

from groq import Groq

from app_config import AppConfig
from common import get_audio_temp_dir
from common import get_ffmpeg_path

app_config = AppConfig()


def convert_audio(input_path):
    out_path = os.path.join(get_audio_temp_dir(), f"{time.time()}.flac")
    cmd = [
        get_ffmpeg_path(),
        "-i",
        input_path,
        "-ar",
        "16000",
        "-ac",
        "1",
        "-map",
        "0:a",
        "-c:a",
        "flac",
        out_path,
    ]
    try:
        subprocess.run(cmd, check=True)
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
    return out_path


def call_groq_api(video_path, model_name="whisper-large-v3-turbo"):
    api_key = app_config["groq_api_key"]
    client = Groq(
        api_key=api_key,
        # base_url="https://empty-eagle-58.deno.dev/api.groq.com"
    )
    prompt = "在标点符号处拆分段落"
    audio_path = convert_audio(video_path)
    try:
        with open(audio_path, "rb") as file:
            s = file.read()
            transcription = client.audio.transcriptions.create(
                file=(audio_path, s),
                model=model_name,
                response_format="verbose_json",
                language="zh",
                temperature=0.2,
                prompt=prompt,
            )
            return transcription.segments
    finally:
        if os.path.exists(audio_path):
            os.remove(audio_path)
